package com.example.vendingmachine.service.impl;

import com.example.vendingmachine.dto.ProductDTO;
import com.example.vendingmachine.dto.ProductQuery;
import com.example.vendingmachine.entity.Product;
import com.example.vendingmachine.mapper.ProductMapper;
import com.example.vendingmachine.service.ProductService;
import com.example.vendingmachine.service.SlotService;
import com.example.vendingmachine.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品服务实现类
 */
@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {

    private final ProductMapper productMapper;
    private final SlotService slotService;

    @Override
    public PageInfo<Product> listProducts(ProductQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return new PageInfo<>(productMapper.selectList(query));
    }

    @Override
    public Product getProductById(Long id) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        return product;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createProduct(ProductDTO productDTO) {
        Product product = new Product();
        BeanUtils.copyProperties(productDTO, product);
        // 设置状态为启用
        product.setStatus("ENABLED");

        productMapper.insert(product);
        return product.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProduct(ProductDTO productDTO) {
        // 检查商品是否存在
        getProductById(productDTO.getId());

        Product product = new Product();
        BeanUtils.copyProperties(productDTO, product);
        productMapper.update(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProduct(Long id) {
        // 检查商品是否存在
        getProductById(id);
        // 检查商品是否被货道关联
        if (slotService.hasSlotsByProductId(id)) {
            throw new BusinessException("商品已被货道关联，无法删除");
        }
        productMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProductStatus(Long id, String status) {
        // 检查商品是否存在
        getProductById(id);
        productMapper.updateStatus(id, status);
    }

    @Override
    public int getTotalStock(Long id) {
        // 检查商品是否存在
        getProductById(id);
        return productMapper.selectTotalStock(id);
    }
} 